package com.redxiii.tracplus.web.util;

import java.io.IOException;
import java.io.Writer;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.view.WebappResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author dfilgueiras
 */
public class TemplateUtility {

	private static final Logger logger = LoggerFactory.getLogger(TemplateUtility.class);
	
	private VelocityEngine ve;
	public TemplateUtility(ServletContext servletContext) {
		
		ve = new VelocityEngine();
		ve.setApplicationAttribute("javax.servlet.ServletContext", servletContext);
		
		Properties props = new Properties();
		
		props.setProperty(VelocityEngine.RESOURCE_LOADER, "webapp");
		props.setProperty("webapp." + VelocityEngine.RESOURCE_LOADER + ".class", WebappResourceLoader.class.getName());
		props.setProperty("webapp." + VelocityEngine.RESOURCE_LOADER + ".path", "/templates/");
		try {
			ve.init(props);
		} catch (Exception e) {
			logger.error("Error initializing Velocity Engine", e);
		}
	}
	
	public boolean printPage(String page, VelocityContext context, Writer writer) {
		try {
			Template template = ve.getTemplate(page);
			template.merge(context, writer);
			
			writer.flush();
			return true;
		} catch (ResourceNotFoundException e) {
			logger.error("Error creating template", e);
		} catch (ParseErrorException e) {
			logger.error("Error creating template", e);
		} catch (MethodInvocationException e) {
			logger.error("Error creating template", e);
		} catch (IOException e) {
			logger.error("Error creating template", e);
		} catch (Exception e) {
			logger.error("Error creating template", e);
		}
		return false;
	}
}
